//
//  BAHeaderNode.m
//  BabyAlbum
//
//  Created by master on 17/2/15.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BAVideoHeader.h"
#import "BAResource.h"
@interface BAVideoHeader () <ASEditableTextNodeDelegate,ASVideoNodeDelegate>

@property (nonatomic, strong) ASVideoNode *coverVideoNode;

@property (nonatomic, strong) ASTextNode *dateNode;
@property (nonatomic, strong) ASDisplayNode *lineNode;
@property (nonatomic, strong) ASEditableTextNode *detailNode;
@property (nonatomic, strong) BAAlbumModel *model;
@property (nonatomic, assign) BOOL isEditing;
@property (nonatomic, copy) void (^selectBlock)(void) ;
@property (nonatomic, copy) void (^textChangeBlock)(NSString *text) ;


@end

@implementation BAVideoHeader

- (BOOL)videoNode:(ASVideoNode*)videoNode shouldChangePlayerStateTo:(ASVideoNodePlayerState)state {
    if(state == ASVideoNodePlayerStatePlaying && _isEditing) {
        return NO;
    }
    return YES;
}

- (instancetype)initWithData:(BAAlbumModel *)model isEdit:(BOOL)isEdit selectPhotoBlock:(void (^)(void))block textChangeBlock:(void (^)(NSString *text))textChangeblock;
{
    if(self = [super init]) {
        self.selectBlock = block;
        self.textChangeBlock = textChangeblock;
        self.model = model;
        _isEditing = isEdit;
        _coverVideoNode = [[ASVideoNode alloc] init];
        _coverVideoNode.backgroundColor = [UIColor whiteColor];
//        NSURL *url = [NSURL fileURLWithPath:model.coverVideo.URL.absoluteString];
        BAAlbumVideoItem *video = (BAAlbumVideoItem *)model.cover;
        _coverVideoNode.asset = video.video;//[AVAsset assetWithURL:url];
        _coverVideoNode.gravity = AVLayerVideoGravityResizeAspect;
        _coverVideoNode.backgroundColor = [UIColor clearColor];
        _coverVideoNode.shouldAutorepeat = YES;
        _coverVideoNode.shouldAutoplay = !isEdit;
        _coverVideoNode.delegate = self;
        _coverVideoNode.userInteractionEnabled = isEdit;
        _coverVideoNode.muted = YES;
        [_coverVideoNode addTarget:self action:@selector(chooseNewImage) forControlEvents:ASControlNodeEventTouchUpInside];
        [self addSubnode:_coverVideoNode];
        
        
        _dateNode = [[ASTextNode alloc] init];
        NSAttributedString *string = [NSAttributedString attributedStringWithString:[model customDateShow] fontSize:11 color:RGBWhite(140)];
        _dateNode.attributedText = string;
        [self addSubnode:_dateNode];
        
        _lineNode = [[ASDisplayNode alloc] init];
        _lineNode.backgroundColor = RGBWhite(140);
        [self addSubnode:_lineNode];
        _detailNode = [[ASEditableTextNode alloc] init];
        string = [NSAttributedString attributedStringWithString:model.desc fontSize:11 color:RGBWhite(140)];
        _detailNode.placeholderEnabled = YES;
        _detailNode.attributedPlaceholderText = [NSAttributedString attributedStringWithString:@"用文字记录难忘瞬间" fontSize:11 color:RGBWhite(180)];
        _detailNode.attributedText = string;
        _detailNode.delegate = self;
        
        if(IS_MAIN_THREAD) {
            NSLog(@"%d",_isEditing);
            //            _detailNode.textView.selectable = NO;
            _detailNode.textView.userInteractionEnabled = _isEditing;
        } else {
            dispatch_sync(dispatch_get_main_queue(), ^{
                NSLog(@"%d",_isEditing);
                //                _detailNode.textView.selectable = NO;
                _detailNode.textView.userInteractionEnabled = _isEditing;
                
            });
        }
        
        if(_isEditing) {
            //            [[XYKeyboardHelper sharedInstance] enableKeyboardHelper];
            [self setUpForDismissKeyboard];
        }
        [self addSubnode:_detailNode];
        //        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resign) name:@"resign" object:nil];
        
    }
    return self;
}

//- (void)resign {
//    [_detailNode.textView resignFirstResponder];
//}

- (BOOL)editableTextNode:(ASEditableTextNode *)editableTextNode shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    return _isEditing;//2be0 fb80
}

- (void)editableTextNodeDidUpdateText:(ASEditableTextNode *)editableTextNode {
    if(self.textChangeBlock) {
        self.textChangeBlock(editableTextNode.textView.text);
    }
}


//- (void)setImage:(UIImage *)image {
//    _coverNode.image = image;
//}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    return NO;
}
//- (UIImage *)image {
//    return _coverNode.image;
//}


- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize
{
//    _coverNode.style.preferredSize = CGSizeMake(constrainedSize.max.width, constrainedSize.max.width);
    _coverVideoNode.style.preferredSize = CGSizeMake(constrainedSize.max.width, constrainedSize.max.width);
    
    _dateNode.style.flexShrink  = YES;
    _lineNode.style.preferredSize = CGSizeMake(kScreenWidth - 40, 1);
    _detailNode.style.flexShrink = YES;
    _detailNode.style.minSize = CGSizeMake(kScreenWidth - 20, 80);
    //    if(!_model.desc.length) {  // 没有文字 为40
    //        _detailNode.style.preferredSize = CGSizeMake(kScreenWidth - 40, 40);
    //    }
    //    ASInsetLayoutSpec *insetLayout = [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(5, 5, 5, 5) child:_coverNode];
    
    ASStackLayoutSpec *ver1 = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionVertical spacing:5 justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsEnd children:@[_coverVideoNode,_dateNode]];
    ASStackLayoutSpec *ver2 = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionVertical spacing:5 justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsCenter children:@[ver1,_lineNode,_detailNode]];
    ASInsetLayoutSpec *insetLayout = [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(5, 5, 5, 5) child:ver2];
    
    
    //    ASStackLayoutSpec *ver3 = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionVertical spacing:5 justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsEnd children:@[insetLayout,_dateNode]];
    //    ASInsetLayoutSpec *insetLayout2 = [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(5, 5, 5, 5) child:ver3];
    
    return [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) child:insetLayout];
}

+ (CGFloat)calculteHeightWithData:(BAAlbumModel *)albumModel {
//    CGFloat descHeight = [albumModel.desc uxy_calculateSize:CGSizeMake(kScreenWidth - 30, CGFLOAT_MAX) font:[UIFont systemFontOfSize:11]].height;
    CGFloat descHeight = [UILabel getHeightByWidth:kScreenWidth - 30 title:albumModel.desc font:[UIFont systemFontOfSize:11]];

    if(descHeight < 10) {
        descHeight = 40;
    }
    CGFloat height = 5 + kScreenWidth - 20 + 5 + 13.5 + 5 + 1+ 5 + descHeight + 20;
    return height;
    
}

//- (UIImage *)cover {
//    return _coverNode.image;
//}
- (NSString *)detailText {
    return _detailNode.textView.text;
}

- (void)chooseNewImage {
    if([_detailNode.textView isFirstResponder]) {
        [self.view endEditing:YES];
        return;
    }
    
    if(!_isEditing) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.selectBlock) {
            self.selectBlock();
        }
        
    });
}

#pragma show and hide the keyboard
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [KEYWINDOW addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [KEYWINDOW removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}
@end
